package com.zmn.plat.admin.controller.standard.record;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.model.entity.standard.read.StandardRead;
import com.zmn.plat.model.entity.standard.read.permission.StandardReadPermission;
import com.zmn.plat.model.entity.standard.record.StandardRecord;
import com.zmn.plat.model.entity.standard.record.StandardRecordQuery;

/**
 * 标准列表
 *
 * @author linfeng
 * @since 2020-02-12 10:23:38
 */
@RestController
@RequestMapping("/standard/record/")
public class StandardRecordModifyController extends StandardRecordBaseController {

    /**
     * 新增修改基本信息
     *
     * @param standardRecord
     * @author linfeng
     * @since 2020-02-12 10:23:38
     */
    @RequestMapping(value = "addEditDetail")
    @RequiresPermissions("/standard/record/addEditDetail.action")
    public ResponseDTO addEditDetail(HttpServletRequest request, @RequestBody StandardRecord standardRecord) {
        Date now = DateUtil.getNow();

        Integer standardId = standardRecord.getStandardId();
        try {
            StandardRecordQuery query = new StandardRecordQuery();
            query.setStatus(GlobalConsts.YES);
            query.setTitle(standardRecord.getTitle());
            List<StandardRecord> list = standardRecordService.listByQuery(query);
            if (standardId == null || standardId == 0) {
                if (list != null && list.size() > 0) {
                    return ResponseDTO.fail("存在相同文件名文章，请先停用同名文章或修改当前文章名称！");
                }
                standardRecord.setCreater(getMcStaffRealName());
                standardRecord.setCreateTime(now);
                standardRecord.setStatus(GlobalConsts.NO);
                standardRecord.setSort(1);
                standardRecord.setReadCount(0);
                standardRecordService.insert(standardRecord);
            } else {
                if (list != null && list.size() > 0) {
                    if (list.size() > 1 || list.get(0).getStandardId().intValue() != standardRecord.getStandardId().intValue()) {
                        return ResponseDTO.fail("存在相同文件名文章，请先停用同名文章或修改当前文章名称！");
                    }
                }

                standardRecord.setUpdater(getMcStaffRealName());
                standardRecord.setUpdateTime(now);
                if (standardRecord.getSort() == null) {
                    standardRecord.setSort(1);
                }
                standardRecordService.updateBaseInfoByKey(standardRecord);
            }

            return ResponseDTO.success(Integer.toString(standardRecord.getStandardId()), "操作成功！");
        } catch (Exception ex) {
            logger.error(
                String.format("[zmn]新增/修改标准失败,standardRecord:[%s],ex:[%s]", JSONObject.toJSONString(standardRecord), ex.getMessage()));
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     * 修改排序
     *
     * @param id
     * @param sort
     * @author linfeng
     * @since 2020-02-12 10:23:38
     */
    @RequestMapping(value = "updateSort")
    @RequiresPermissions("/standard/record/list.action")
    public ResponseDTO updateSort(HttpServletRequest request, @RequestParam(value = "id", defaultValue = "0") Integer id,
        @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (id == 0) {
            return ResponseDTO.fail("请选择要更改排序的数据！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置排序值！");
        }

        Integer result = standardRecordService.updateSortByKey(id, sort, getMcStaffRealName());
        return ResponseDTO.success(result, "操作成功！");
    }

    /**
     * 修改状态
     *
     * @param ids
     * @param status
     * @author linfeng
     * @since 2020-02-12 10:23:38
     */
    @RequestMapping(value = "updateStatus")
    @RequiresPermissions("/standard/record/updateStatus.action")
    public ResponseDTO updateStatus(HttpServletRequest request, @RequestParam(value = "ids", defaultValue = "") String ids,
        @RequestParam(value = "status", defaultValue = "0") Integer status) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的数据！");
        }
        if (status == 0) {
            return ResponseDTO.fail("请设置状态！");
        }

        List<Integer> arrayIds = StringUtil.convertStrsToList(ids);

        Integer result = standardRecordService.updateStatusBatchByKey(arrayIds, status, getMcStaffRealName());
        return ResponseDTO.success(result, "操作成功！");
    }

    @RequestMapping(value = "addEditContent")
    @RequiresPermissions("/standard/record/addEditContent.action")
    @ResponseBody
    public ResponseDTO addEditContent(HttpServletRequest request, @RequestBody StandardRecord standardRecord) {
        if (standardRecord.getStandardId() == 0) {
            return ResponseDTO.fail("标准ID不正确，不能为0！");
        }

        StandardRecord record = standardRecordService.findByKey(standardRecord.getStandardId());
        if (record == null) {
            record = new StandardRecord();
        }
        record.setContent(standardRecord.getContent());
        record.setFileSrc(standardRecord.getFileSrc());
        record.setFileSize(standardRecord.getFileSize());
        record.setFileSrc2(standardRecord.getFileSrc2());
        record.setFileSize2(standardRecord.getFileSize2());
        record.setFileSrc3(standardRecord.getFileSrc3());
        record.setFileSize3(standardRecord.getFileSize3());
        record.setFileSrc4(standardRecord.getFileSrc4());
        record.setFileSize4(standardRecord.getFileSize4());
        record.setFileSrc5(standardRecord.getFileSrc5());
        record.setFileSize5(standardRecord.getFileSize5());
        record.setUpdater(getMcStaffRealName());
        Date now = DateUtil.getNow();
        record.setUpdateTime(now);
        standardRecordService.updateByKey(record);

        return ResponseDTO.success(record.getStandardId(), "操作成功！");
    }

    @RequiresPermissions("/standard/record/permission/save.action")
    @RequestMapping(value = "permission/save")
    @ResponseBody
    public ResponseDTO save(@RequestParam(value = "ids") List<String> ids,
        @RequestParam(value = "standardId", defaultValue = "0") int standardId) {
        if (standardId == 0) {
            return ResponseDTO.fail("参数异常");
        }
        LoginStaff mcStaff = getMcStaff();

        // 删除标准所有阅读权限
        standardReadPermissionService.deleteByStandardId(standardId);

        List<StandardReadPermission> list = ids.stream().map(deptId -> {
            StandardReadPermission standardReadPermission = new StandardReadPermission() {
                {
                    setOrgId(Integer.valueOf(deptId));
                    setStandardId(standardId);
                    setCreater(mcStaff.getRealName());
                    setCreateTime(DateUtil.getNow());
                }
            };
            return standardReadPermission;
        }).collect(Collectors.toList());
        standardReadPermissionService.insertBatch(list);

        return ResponseDTO.success(null, "保存成功!");
    }

    @RequestMapping(value = "read")
    @ResponseBody
    public ResponseDTO read(@RequestParam(value = "standardId", defaultValue = "0") int standardId) {
        if (standardId == 0) {
            return ResponseDTO.fail("参数异常");
        }
        LoginStaff mcStaff = getMcStaff();
        StandardRead standardRead = new StandardRead();
        standardRead.setStandardId(standardId);
        standardRead.setStaffId(mcStaff.getStaffId());
        standardRead.setCreater(mcStaff.getRealName());
        standardRead.setCreateTime(DateUtil.getNow());
        // 已阅读并同意
        standardReadService.insert(standardRead);
        standardRecordService.incrReadCount(standardId);
        return ResponseDTO.success();
    }

    @RequestMapping(value = "countFiles")
    public ResponseDTO countFiles(Integer standardId) {
        Integer size = standardRecordBService.countFiles(standardId);
        if (NumberUtil.isNullOrZero(size)) {
            return ResponseDTO.fail("该条记录无附件！");
        }
        return ResponseDTO.success(size, GlobalConsts.SUCCESS_MSG);
    }
}
